<template>
  <view>
    <view class="common">
      <u--form labelPosition="left" :model="dataForm.userInfo" :rules="rules" ref="userForm">
        <u-form-item label="姓名" prop="name" borderBottom required>
          <u-input v-model="dataForm.userInfo.name" border="none" clearable>
          </u-input>
        </u-form-item>
        <!--<editor-fold desc="FIXME 修改为上传头像">-->
        <!--<u-form-item label-width="70" label="头像地址" prop="avatar" border-bottom>-->
        <!--  <u-input-->
        <!--      v-model="dataForm.userInfo.avatar"-->
        <!--      border="none"-->
        <!--      clearable>-->
        <!--    <template slot="prefix">-->
        <!--      <u-text text="https://" margin="0 5px 0 0" type="info"></u-text>-->
        <!--    </template>-->
        <!--    <template slot="suffix">-->
        <!--      <u-button @click=""-->
        <!--                :custom-style="{'border': 'none'}"-->
        <!--                :hairline="false"-->
        <!--                icon="photo">-->
        <!--      </u-button>-->
        <!--    </template>-->
        <!--  </u-input>-->
        <!--  <u-modal-->
        <!--      @close=""-->
        <!--      :show="dataForm.control.coverVisible"-->
        <!--      :show-confirm-button="false"-->
        <!--      close-on-click-overlay>-->
        <!--    <template slot="default">-->
        <!--      <u-image-->
        <!--          @click="coverVisibleSwitch"-->
        <!--          showLoading-->
        <!--          height="400"-->
        <!--          width="250"-->
        <!--          mode="aspectFit"-->
        <!--          :src="`https://${dataForm.bookInfo.cover}`">-->
        <!--      </u-image>-->
        <!--    </template>-->
        <!--  </u-modal>-->
        <!--</u-form-item>-->
        <!--</editor-fold>-->
        <u-form-item label-width="70" label="手机号码" prop="tel" border-bottom required>
          <u-input v-model="dataForm.userInfo.tel" type="number" border="none" clearable>
          </u-input>
        </u-form-item>
        <u-form-item label-width="70" label="电子邮箱" prop="email" border-bottom required>
          <u-input v-model="dataForm.userInfo.email" border="none" clearable>
          </u-input>
        </u-form-item>
        <u-form-item label="角色" prop="role" required>
          <u-radio-group @change="roleChange()" v-model="dataForm.userInfo.role" placement="row">
            <u-radio label="普通用户" :name="0"></u-radio>
            <u-radio :customStyle="{marginLeft: '15px'}" label="管理员" :name="1"></u-radio>
          </u-radio-group>
        </u-form-item>
      </u--form>
      <u-button :custom-style="{'margin-top': '15px'}"
                type="success"
                shape="circle"
                text="提交"
                @click="saveOrUpdateUser()">
      </u-button>
      <u-button v-if="type"
                :custom-style="{'margin-top': '15px'}"
                type="error"
                shape="circle"
                text="删除此用户"
                @click="deleteUser()">
      </u-button>
    </view>

  </view>
</template>

<script>
export default {
  onLoad(query) {
    let type = Number(query.type)
    if (type)
      this.dataForm.userInfo = JSON.parse(query.user)
    this.type = type
    console.log(this.dataForm.userInfo)
  },
  onReady() {
    this.$refs.userForm.setRules(this.rules)
  },
  data() {
    return {
      type: 0,
      dataForm: {
        userInfo: {
          role: 0
        }
      },
      rules: {
        name: {
          required: true,
          message: '请填写用户名!',
          trigger: 'blur'
        },
        tel: [
          {
            required: true,
            message: '请填写手机号!',
            trigger: 'blur'
          },
          {
            validator: (rule, value) => {
              return uni.$u.test.mobile(value)
            },
            message: '请填写正确的手机号码!',
            trigger: ['change', 'blur']
          }
        ],
        email: [
          {
            required: true,
            message: '请输入邮箱',
            trigger: 'blur'
          },
          {
            validator: (rule, value) => {
              return uni.$u.test.email(value)
            },
            message: '请填写正确的邮箱!',
            trigger: ['change', 'blur']
          }
        ]
      }
    }
  },
  methods: {
    roleChange(value) {
      this.dataForm.userInfo.role = value
    },
    saveOrUpdateUser() {
      this.$refs.userForm.validate().then(() => {
        let db = uniCloud.database()
        if (this.type) {
          db.collection('user').doc(this.dataForm.userInfo._id).update({
            name: this.dataForm.userInfo.name,
            tel: this.dataForm.userInfo.tel,
            email: this.dataForm.userInfo.email,
            role: this.dataForm.userInfo.role
          }).then(() => {
            uni.showToast({
              title: '修改成功!',
              icon: 'success'
            })
          }).catch(err => {
            uni.showToast({
              title: err.message || '修改失败!',
              icon: 'error'
            })
          }).finally(() => {
            setTimeout(() => {
              uni.navigateBack({})
            }, 1000)
          })
        } else {
          db.collection('user').add(this.dataForm.userInfo).then(() => {
            uni.showToast({
              title: '新增成功!',
              icon: 'success'
            })
          }).catch(err => {
            uni.showToast({
              title: err.message || '新增失败!',
              icon: 'error'
            })
          }).finally(() => {
            setTimeout(() => {
              uni.navigateBack({})
            }, 1000)
          })
        }
      }).catch(err => {
      })
    },
    // TODO 若该书籍与用户存在关联，则无法删除
    deleteUser() {
      let _this = this
      uni.showModal({
        title: '删除用户',
        content: '是否删除此用户?',
        success(res) {
          if (res.confirm) {
            uniCloud.database().collection('user').doc(_this.dataForm.userInfo._id).remove().then(() => {
              uni.showToast({
                title: '删除成功!',
                icon: 'success'
              })
            }).catch(err => {
              uni.showToast({
                title: err.message || '删除失败!',
                icon: 'error'
              })
            }).finally(() => {
              setTimeout(() => {
                uni.navigateBack({})
              }, 1000)
            })
          }
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
